package notes.java.java8.demo;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Stream API
 * 终止操作
 *
 */
public class J7_TestStream3 {
	
	public static void main(String[] args) {
		List<String> list = new ArrayList<>();
		list.add("zhangsan");
		list.add("wangwu");
		list.add("liuqiadson");
		list.add("wangwu");
		Stream<String> stream = list.stream();
		// 1、查看与匹配
		// 1.1、allMatch，完全匹配
//		boolean b = stream.allMatch((x)->x.equals("wangwu"));// 都equals wangwu才返回true
//		System.out.println(b);
		// 1.2、anyMatch，部分匹配
//		boolean b1 = stream.anyMatch((x)->x.equals("wangwu")); // 有一个equals wangwu 就返回true
//		System.out.println(b1);
		// 1.3、noneMathc，无匹配
//		boolean b2 = stream.noneMatch((x)->x.equals("abc"));  // 都不equals abc才返回true
//		System.out.println(b2);
		// 1.4、findFirst，第一个元素
//		Optional<String> str = stream.findFirst();
//		System.out.println(str.get());
		// 1.5、findAny，任意一个
//		Optional<String> str2 = stream.findAny();
//		System.out.println(str2.get());
		// 1.6、count，流的大小
//		long size = stream.count();
//		System.out.println(size);
		// 1.7、max，流中的最大值
//		Optional<String> str3 = stream.max(Comparator.comparing((x)->x.toString().length()));
//		System.out.println(str3.get());
		// 1.8、min，流中的最小值
//		Optional<String> str4 = stream.min(Comparator.comparing((x)->x.toString().length()));
//		System.out.println(str4.get());
		
		List<Integer> nums = Arrays.asList(1, 2, 3, 4, 4, 6, 7);
		Stream<Integer> stream2 = nums.stream();
		// 2、reduce 归约，反复的结合，返回一个最终结果
//		int sum = stream2.reduce(0, (x, y)-> x + y);
//		System.out.println(sum);
		
		// 3、collect 收集
		List<Emp> emps = new ArrayList<>();
		emps.add(new Emp(1, "zhangsan", true));
		emps.add(new Emp(2, "wangwu", true));
		emps.add(new Emp(3, "zhaoliu", false));
		Stream<Emp> stream3 = emps.stream();
		Set<Integer> set = stream2.collect(Collectors.toSet());
		System.out.println(set);
		// 按是否marry分组
		Map<Boolean, List<Emp>> mm = stream3.collect(Collectors.groupingBy(Emp::isMarry));
		for(Boolean b : mm.keySet()) {
			List<Emp> ems = mm.get(b);
			System.out.println(ems);
		}
	}

}


class Emp {
	private int id;
	private String name;
	private boolean marry;
	public Emp(int id, String name, boolean marry) {
		this.id = id;
		this.name = name;
		this.marry = marry;
	}
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public boolean isMarry() {
		return marry;
	}
	public void setMarry(boolean marry) {
		this.marry = marry;
	}

	@Override
	public String toString() {
		return "id:" + this.getId() +  "\t name:" + this.getName() + "\t marry:" + this.isMarry();
	}
	
}